package com.wulwu.rocketmq.practice.order.producer;

import com.wulwu.rocketmq.practice.order.OrderInfo;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.MessageQueueSelector;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;
import org.apache.rocketmq.remoting.exception.RemotingException;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Description 顺序发送者
 * @Author wuxb
 * @Date 2022/4/13 14:11
 */
public class Producer {

    public static void main(String[] args) throws MQClientException, MQBrokerException, RemotingException, InterruptedException {
        //1.创建消息生产者producer，并制定生产者组名
        DefaultMQProducer producer = new DefaultMQProducer("orderGroup");
        //2.指定Nameserver地址
        producer.setNamesrvAddr("127.0.0.1:9876");
        //3.启动producer
        producer.start();

        List<OrderInfo> orderInfos = OrderInfo.buildOrders();
        for (int i = 0; i < orderInfos.size(); i++) {
            OrderInfo orderInfo = orderInfos.get(i);
            Long orderId = orderInfo.getOrderId();
            String content = orderInfo.toString();

            //4.创建消息对象，指定主题Topic、Tag和消息体
            Message message = new Message("orderTopic", "orderTag", content.getBytes(StandardCharsets.UTF_8));
            //5.发送消息 顺序消息核心就是指定同意队列
            SendResult sendResult = producer.send(message, new MessageQueueSelector() {
                @Override
                public MessageQueue select(List<MessageQueue> mqs, Message msg, Object arg) {
                    Long businessId = (Long) arg;
                    long index = businessId % mqs.size();
                    MessageQueue messageQueue = mqs.get((int) index);
                    return messageQueue;
                }
            }, orderId);
            SendStatus sendStatus = sendResult.getSendStatus();
            String msgId = sendResult.getMsgId();
            int queueId = sendResult.getMessageQueue().getQueueId();
            System.out.println("发送状态：" + sendStatus + ", 消息ID：" + msgId + ", 对列：" + queueId);

            TimeUnit.SECONDS.sleep(1);
        }
        //6.关闭生产者producer
        producer.shutdown();
    }



}
